<?php 
function createClientView($view){
	//echo json_encode($view);
	global $wpdb;
	if($view->user == 0){
?>

	<!--div>
		<fieldset>
			<form id="register_form" method="POST" action="<?php echo get_admin_url().'admin-post.php'; ?>">
				<input type="hidden" name="action" value="submit-form">
				<input type="text" name="client_name" required placeholder="Логин"><br> 
				<input type="text" name="client_fullname" required placeholder="Имя пользователя"><br> 
				<input type="text" name="client_email" required placeholder="e-mail"><br> 
				<input type="password" name="client_password" required placeholder="пароль"><br> 
				<input type="password" name="client_password2" required placeholder="повтор пароля"><br> 

				<input type="submit" name="Зарегестрироваться" value="Зарегестрироваться"></submit>
			</form>
		</fieldset>		
	</div-->

<style>
	.h3 {
		color:grey;
	}

</style>


<?php 
	}elseif( $view->role["role_status"] <= 2 ) {


	
	$arr_table = array('client', 'course');	
	$res_res_for_select = array();
	foreach ($arr_table as $table_name) {
		$table = new TableORM($table_name);
		$res_res_for_select[$table_name] = $table->findAllForSelect();
		
	}
	
	$prefix = "timetable_";

	/*$teacher_query = "SELECT 
						teacher_id,
						teacher_name,
						course_id,
						course_name
					FROM 
						{$prefix}teachercourse, {$prefix}teacher, {$prefix}course
					WHERE
							 teacher_id = idteacher AND course_id = idcourse";*/
	$arr_teacher_res = array();						 

	$teacher_query = "SELECT 
						idteacher teacher_id,
						teacher_name
					FROM 
						{$prefix}teacher;";


	$arr_teacher = $wpdb->get_results($teacher_query, ARRAY_A);

	$course_query = "SELECT idcourse course_id, course_name FROM {$prefix}course";
	$arr_courses = $wpdb->get_results($course_query, ARRAY_A);

	$course_assoc_query = "SELECT course_id, course_name, teacher_id, teacher_name FROM {$prefix}teachercourse, {$prefix}course, {$prefix}teacher  WHERE idcourse=course_id AND idteacher=teacher_id"  ;
	$arr_course_assoc = $wpdb->get_results($course_assoc_query , ARRAY_A);
	
	/*echo json_encode($arr_teacher) ."<br>";
	echo json_encode($arr_courses) ."<br>";
	echo json_encode($arr_course_assoc) ."<br>";*/

	foreach ($arr_teacher as $teacher) {

		$id = $teacher['teacher_id'];
		$name = $teacher['teacher_name'];
		$data = array();
		$sel = array();
		$data_ids = array();
		foreach ($arr_course_assoc as $course_assoc) {
					if($id == $course_assoc['teacher_id']){
						$data[] = $course_assoc;
						$data_ids[] = $course_assoc['course_id'];
				}
		}	

		foreach ($arr_courses as $course) {
			if( !in_array($course['course_id'], $data_ids) ){
				$sel[] = $course;
			}
		}		

		$arr_teacher_res[] = array(
			"id"=>$id,
			"name"=>$name,
			"data"=>$data,
		"select"=>$sel 
		);

	}
	
	//echo json_encode($arr_teacher_res);


?>


	<div>
		<br><br>
		<h3 class=" h3 part_header"> Управление профилями </h3>
		<h3 id="click_form_reg" class="h3 form_header" > Добавление пользователя <span id="click_form_reg_v"> >> </span> 	 </h3> 
		<div id="form_reg" style="display: none;">
			<fieldset>
				<form id="register_form" name="register_form" method="POST" action="">
					<input type="hidden" name="action" value="submit-form">
					<input type="text" name="client_name" required placeholder="Логин"><br> 
					<input type="text" name="client_fullname" required placeholder="Имя пользователя"><br> 
					<input type="text" name="client_email" required placeholder="e-mail"><br> 
					<select name="role">
						<option value="5">Клиент</option>	
						<option value="3">Преподаватель</option>	
						<option value="1">Администратор</option>	
					</select><br>
					<input type="password" name="client_password" required placeholder="пароль"><br> 
					<input type="password" name="client_password2" required placeholder="повтор пароля"><br> 
					<input type="submit" name="Зарегестрироваться" value="Регистрировать"></submit><br>

					<span id="err_regform"></span>
				</form>
			</fieldset>
		</div>
		<hr>
		<h3 id="click_form_add_course" class="h3 form_header" > Добавление курсов (Клиенты) <span id="click_form_add_course_v"> >> </span> 	 </h3> 
		<div id="form_add_course" style="display: none;">
			<fieldset>
				<form id="add_course_form" name="register_form" method="POST" action="">
					<input type="hidden" name="action" value="submit-form">
					<select name="client">  
						<?php foreach($res_res_for_select['client']['values'] as $value){  ?>
							<option value="<?php echo $value['client_id']; ?>"> <?php echo $value['client_name']; ?> </option>
						<?php } ?>
					</select>
					<select name="course">  
						<?php foreach($res_res_for_select['course']['values'] as $value){  ?>
							<option value="<?php echo $value['course_id']; ?>"> <?php echo $value['course_name']; ?> </option>
						<?php } ?>
					</select>
					<input type="text" placeholder="Сумма курса (не базовая)" name="summ">
					<input type="text" placeholder="Дата начала курса" id="date_reg" name="date">
					<input type="submit" name="submit" value="Записать">
				</form>
			</fieldset>
		</div>
		<hr>
		<h3 id="click_form_add_course_teacher" class="h3 form_header" > Добавление курсов (Преподаватели) <span id="click_form_add_course_teacher_v"> >> </span> 	 </h3> 
		<div id="form_add_course_teacher" style="display: none;">
			



			<ul  class="list-unstyled" data-bind="foreach:teacherView">
				<li>
					<span data-bind="ifnot:state().expand, click:changestate "> <span class="glyphicon glyphicon-plus"></span>  </span>
					<span data-bind="if:state().expand, click:changestate"> <span class="glyphicon glyphicon-minus"></span>  </span>
					<span data-bind="text:name"></span>
						<div data-bind="if:state().expand">
						<ol  data-bind="foreach:model">
							<li class="li-course"> <span data-bind="text:course_name"></span> <span class="glyphicon glyphicon-remove" data-bind="click:del"></span> </li>
						</ol>
						
						<select data-bind="options:select, optionsText:'course_name', value:selectValue "> 
						</select> <span class="glyphicon glyphicon-ok" data-bind="click:addcourse"></span> 	
						</div>	

				</li>
			</ul>

		</div>


	</div>

	<script type="text/javascript">
		var teacher_and_courses = <?php echo json_encode($arr_teacher_res); ?>			
		//console.log(teacher_and_courses);
	</script>
	<script>
		jQuery(function(){

				


				var supLoc = function(){
					try {
					    return 'localStorage' in window && window['localStorage'] !== null;
					} catch (e) {
					    return false;
					}
				}

				window.supportLocalStorage = window.supportLocalStorage	|| supLoc;


			//datepicker


				var picka_option =  {
						format:"dd-mm-yyyy",
				   		monthsFull: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
						weekdaysShort: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб' ],
						today: 'Сегодня',
						clear: 'Очистить',
						close: 'Закрыть',
						formatSubmit: 'dd-mm-yyyy'		        	
			    };
			    
			    jQuery("#date_reg").pickadate(picka_option);


		    	/*
		        jQuery.datepicker.regional['ru'] = {
	                closeText: 'Закрыть',
	                prevText: '&#x3c;Пред',
	                nextText: 'След&#x3e;',
	                currentText: 'Сегодня',
	                monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь',
	                'Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
	                monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн',
	                'Июл','Авг','Сен','Окт','Ноя','Дек'],
	                dayNames: ['воскресенье','понедельник','вторник','среда','четверг','пятница','суббота'],
	                dayNamesShort: ['вск','пнд','втр','срд','чтв','птн','сбт'],
	                dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
	                dateFormat: 'dd.mm.yy', firstDay: 1,
	            	isRTL: false
	            };		        
	            jQuery.datepicker.setDefaults(
	            	jQuery.datepicker.regional['ru']    
				);

	            var options ={
					altField: "#alternate",
					dateFormat:"dd-mm-yy"
				};

		        $el.datepicker(options);
				*/
				

		    //view     


		    var changeLocalStorage = function(key){
		    	if( supportLocalStorage() ){
		    		var varname = "timetable_" + key;
		    		localStorage[varname] = 1 - localStorage[varname];
		    	}
		    }

			jQuery("#click_form_reg").click(function(){
				var butText = jQuery("#click_form_reg_v").text();
				if(butText == " >> "){
					butText = " V ";
				}else{
					butText = " >> ";
				}
				jQuery("#click_form_reg_v").text(butText);
				jQuery("#form_reg").toggle();
				changeLocalStorage("form_reg");
			});

			jQuery("#click_form_add_course").click(function(){
				var butText = jQuery("#click_form_add_course_v").text();
				if(butText == " >> "){
					butText = " V ";
				}else{
					butText = " >> ";
				}
				
				jQuery("#click_form_add_course_v").text(butText);
				jQuery("#form_add_course").toggle();
				changeLocalStorage("form_add_course");
			});

			jQuery("#click_form_add_course_teacher").click(function(){
				var butText = jQuery("#click_form_add_course_teacher_v").text();
				if(butText == " >> "){
					butText = " V ";
				}else{
					butText = " >> ";
				}
				
				jQuery("#click_form_add_course_teacher_v").text(butText);
				jQuery("#form_add_course_teacher").toggle();
				changeLocalStorage("form_add_course_teacher");

			});

			//send

			jQuery('#register_form').submit(function(){
				//console.log("reg");
				var submit_obj = {};
				jQuery.each(jQuery("#register_form")[0].elements, function(id, val){ 
					submit_obj[val.name] = val.value;
				});
				var dataS = {
					table_method : "register",
					table_data : submit_obj,
					table_name: ''
				}
				jQuery.ajax({
						type:'POST',
						url:ajaxurl + "?action=test_ajax",
						data:dataS	
					})
					.done(function(resp){
						//console.log(resp);
						jQuery("#register_form [name=client_name]").val('');
						jQuery("#register_form [name=client_fullname]").val('');
						jQuery("#register_form [name=client_email]").val('');
						window.location.reload();
				    });
				return false;
			});


			jQuery('#add_course_form').submit(function(){
				//console.log("add");
				var submit_obj = {};
				jQuery.each(jQuery("#add_course_form")[0].elements, function(id, val){ 
					submit_obj[val.name] = val.value;
				});
				submit_obj.table_name = 'client';
				var dataS = {
					table_method : "addcourse",
					table_data : submit_obj,
					table_name: ''
				}
				jQuery.ajax({
						type:'POST',
						url:ajaxurl + "?action=test_ajax",
						data:dataS	
					})
					.done(function(resp){
						//console.log(resp);
						window.location.reload();
				    });
				return false;
			});



			if( supportLocalStorage() ){
				var arrIdsInLocal = [
					{
						main: 'form_reg',
						button: 'click_form_reg_v'
					},
					{
						main: 'form_add_course',
						button: 'click_form_add_course_v'
					},
					{
						main: 'form_add_course_teacher',
						button: 'click_form_add_course_teacher_v'
					}
				];

				_.each(arrIdsInLocal, function(it){
					key = "timetable_" + it.main;
					var val = localStorage[key];
					if(val === undefined){
						val = 0;
						localStorage[key] = val;
					}
					if(val == 1){
						$("#"+it.main).toggle();	
						$("#"+it.button).text(" V ");
					}
				});
			}
		});
	</script>	

<?php 
	}elseif( $view->role["role_status"] >= 5 ) {
?>

	<div>

		<h2>Клиент  <?php echo $view->user['client_name']; ?> </h2>

		<h3 class="h3 ">Курсы клиента</h3>
		<ul data-bind="foreach: profile_courses">
			<li>
				<span data-bind="text:course_name">
					
				</span>
			</li>
		</ul>	

	</div>

	<script>
		var profile_courses = <?php echo $view->courses(); ?> ;
	</script>

<?php 
	}elseif( $view->role["role_status"] >= 3 || $view->role["role_status"] <= 4  ) {
?>

	<div>
		<h2>Преподаватель   <?php echo $view->user['teacher_name']; ?> </h2>
		<h3 class="h3 ">Курсы преподователя</h3>


		<ul data-bind="foreach: profile_courses">
			<li>
				<span data-bind="text:course_name">
					
				</span>
			</li>
		</ul>	

	</div>

	<script>
		var profile_courses = <?php echo $view->courses(); ?> ;
	</script>


<?php 
	}else{}
?>


<?php
}
?>